package com.bestv.search.management.command;

import com.bestv.search.common.dataSource.DataSourceKey;
import com.bestv.search.common.model.SysRole;
import com.bestv.search.common.model.SysUser;
import com.bestv.search.common.service.SysRoleManager;
import com.bestv.search.common.util.CommandException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class RoleCommand {
    protected final Log log = LogFactory.getLog(RoleCommand.class);
    private SysRoleManager roleManager;

    public SysRoleManager getRoleManager() {
        return roleManager;
    }

    public void setRoleManager(SysRoleManager roleManager) {
        this.roleManager = roleManager;
    }

    public String find(SysUser user, Map<String, String[]> map, DataSourceKey dsKey) throws CommandException {
        String result = "";

        List<SysRole> roles = roleManager.getRoles(dsKey);
        try {
            JSONArray jsonArray = rolesToJson(roles);
            result = "{'roles':" + jsonArray.toString() + "}";
        } catch (JSONException e) {
            log.error(e);
            throw new CommandException();
        }
        return result;
    }

    private JSONObject roleToJson(SysRole role) throws JSONException {
        JSONObject jObj = new JSONObject();
        jObj.put("id", role.getId());
        jObj.put("name", role.getName());
        jObj.put("description", role.getDescription());
        return jObj;
    }

    private JSONArray rolesToJson(List<SysRole> roles) throws JSONException {
        List<JSONObject> list = new ArrayList<JSONObject>();
        for (SysRole role : roles) {
            list.add(roleToJson(role));
        }
        JSONArray jsonArray = new JSONArray(list.toArray());
        return jsonArray;
    }
}
